// 文件: controllers/JobController.js
const connection = require("../../config/mysql.js");

class JobController {
    /**
 * 获取职业列表（基础职业）
 * GET /api/user/jobs
 */
    static async getJobClasses(ctx) {
        try {
            const query = `
                SELECT 
                  id,
                  name,
                  job_type,
                  description,
                  base_hp,
                  base_mp,
                  base_attack,
                  base_defense,
                  base_speed,
                  primary_weapon_type,
                  armor_preference,
                  icon_url,
                  level
                FROM job_classes 
                WHERE level = 1 AND is_active = TRUE
                ORDER BY sort_order, id
              `;

            const [rows] = await connection.execute(query);

            ctx.body = {
                code: 200,
                msg: "职业列表获取成功",
                data: rows,
            };
        } catch (error) {
            console.error("查询职业列表失败:", error);
            ctx.status = 500;
            ctx.body = {
                code: 500,
                msg: "服务器内部错误",
            };
        }
    }
    /**
     * 1. 获取当前职业及前置职业的数据列表（从最老祖宗到当前职业）
     */
    static async getCurrentAndPreJobs(ctx) {
        const { jobId } = ctx.request.body;

        if (!jobId) {
            ctx.status = 400;
            ctx.body = { code: 400, msg: "职业ID不能为空" };
            return;
        }

        try {
            let jobsList = [];
            let currentId = jobId;

            // 向上追溯 parent_id 链
            while (currentId) {
                const [rows] = await connection.execute(
                    `SELECT 
            id, name, level, parent_id, job_type, 
            required_level, is_active, icon_url
           FROM job_classes 
           WHERE id = ?`,
                    [currentId]
                );

                if (rows.length === 0) {
                    ctx.status = 400;
                    ctx.body = { code: 400, msg: `未找到职业ID: ${currentId}` };
                    return;
                }

                const job = rows[0];
                jobsList.unshift(job); // 头部插入，保证顺序为 祖先 → 当前
                currentId = job.parent_id; // 继续查父级
            }

            ctx.body = {
                code: 200,
                msg: "成功获取职业及前置职业列表",
                data: jobsList,
            };

        } catch (error) {
            console.error("获取职业及前置职业失败:", error);
            ctx.status = 500;
            ctx.body = { code: 500, msg: "服务器内部错误，请稍后重试" };
        }
    }

    /**
     * 2. 获取基础职业的职业树（包含所有后代）
     */
    static async getJobTreeById(ctx) {
        const { jobId } = ctx.request.body;

        if (!jobId) {
            ctx.status = 400;
            ctx.body = { code: 400, msg: "职业ID不能为空" };
            return;
        }

        try {
            const tree = await JobController._buildJobTree(jobId);

            if (!tree) {
                ctx.status = 400;
                ctx.body = { code: 400, msg: "未找到该基础职业" };
                return;
            }

            ctx.body = {
                code: 200,
                msg: "成功获取职业树",
                data: tree,
            };

        } catch (error) {
            console.error("获取职业树失败:", error);
            ctx.status = 500;
            ctx.body = { code: 500, msg: "服务器内部错误，请稍后重试" };
        }
    }

    /**
     * 私有方法：递归构建职业树
     * @param {number} rootId - 根职业ID
     * @param {Set} seenIds - 防止循环引用
     * @returns {Object|null}
     */
    static async _buildJobTree(rootId, seenIds = new Set()) {
        // 防止循环引用
        if (seenIds.has(rootId)) {
            console.warn(`检测到循环引用，跳过职业ID: ${rootId}`);
            return null;
        }
        seenIds.add(rootId);

        // 查询当前节点
        const [rows] = await connection.execute(
            `SELECT 
        id, name, level, parent_id, job_type,
        required_level, is_active, icon_url
       FROM job_classes 
       WHERE id = ? AND is_active = TRUE`,
            [rootId]
        );

        if (rows.length === 0) return null;

        const node = { ...rows[0], children: [] };

        // 查询所有子节点
        const [childrenRows] = await connection.execute(
            `SELECT id FROM job_classes 
       WHERE parent_id = ? AND is_active = TRUE 
       ORDER BY sort_order, id`,
            [rootId]
        );

        for (const child of childrenRows) {
            const childTree = await JobController._buildJobTree(child.id, seenIds);
            if (childTree) {
                node.children.push(childTree);
            }
        }

        return node;
    }

    /**
     * 3. 获取下一级可提升方向列表
     */
    static async getNextLevelJobs(ctx) {
        const { jobId } = ctx.request.body;

        if (!jobId) {
            ctx.status = 400;
            ctx.body = { code: 400, msg: "职业ID不能为空" };
            return;
        }

        try {
            const [rows] = await connection.execute(
                `SELECT 
          id, name, level, job_type, required_level,
          required_job_id, required_skill_ids, required_item_ids,
          is_active, icon_url, description
         FROM job_classes 
         WHERE parent_id = ? AND is_active = TRUE
         ORDER BY sort_order, id`,
                [jobId]
            );

            ctx.body = {
                code: 200,
                msg: rows.length > 0
                    ? "成功获取下一级可提升方向列表"
                    : "当前职业已达顶级或无可进阶职业",
                data: rows,
            };

        } catch (error) {
            console.error("获取下一级可提升方向失败:", error);
            ctx.status = 500;
            ctx.body = { code: 500, msg: "服务器内部错误，请稍后重试" };
        }
    }
}

module.exports = JobController;